import { ref } from "vue";
import { bookServicePerson, customerbrowse } from "@/api/customer";
import { takeServiceOrder } from "@/api/service";

interface BookingParams {
  customerId: number;
  servicePersonId: number;
  serviceId: number;
}

// 预约 API
const mockBookingApi = (bookingData: BookingParams) => {
  return new Promise((resolve, reject) => {
    bookServicePerson(bookingData)
      .then(() => {
        resolve({ message: "预约成功！" });
      })
      .catch(() => {
        reject({ message: "预约时发生错误，请稍后再试！" });
      });
  });
};

export function useBooking() {
  const isLoading = ref(false); // 用于显示加载状态
  const errorMessage = ref(""); // 用于显示错误信息

  //添加到浏览记录
  const getcustomerbrowse = async (servicePersonId: number) => {
    const customerId = uni.getStorageSync("userId");
    if (!customerId) {
      uni.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }
    isLoading.value = true;
    try {
      await customerbrowse({ customerId: customerId, personId: servicePersonId });
      console.log("浏览记录添加成功");
    } catch (error) {
      console.error("添加浏览记录失败:", error);
    } finally {
      isLoading.value = false;
    }
  };

  // 预约服务
  const handleBooking = async (formData: any) => {
    isLoading.value = true;
    errorMessage.value = "";
    try {
      const response: any = await mockBookingApi(formData);
      await uni.showToast({
        title: response.message,
        icon: "success",
      });
    } catch (error: any) {
      errorMessage.value = error.message;
      uni.showToast({
        title: error.message,
        icon: "none",
      });
    } finally {
      isLoading.value = false; // 结束加载
    }
  };

  return {
    isLoading,
    errorMessage,
    handleBooking,
    getcustomerbrowse,
  };
}
